package com.example.cet4try.Utils;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;

import com.example.cet4try.myDialog.LoadDialog;

import java.util.Timer;
import java.util.TimerTask;

public class MyAsyncTask extends AsyncTask {

    private Context context;
    private LoadDialog dialog;
    private int time = 0;
    private int pause = 20;
    private OnExecute onExecute = null;

    public MyAsyncTask(Context context,String title) {
        this.context = context;
        dialog = new LoadDialog(context);
        dialog.setTitle(title);
    }

    @Override
    protected void onPreExecute() {//task前
        dialog.show();

        if (onExecute != null){
            onExecute.before();
        }

        final Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                time++;
                if (time >= 100)
                    timer.cancel();
            }
        }, 0, pause);

        super.onPreExecute();
    }

    @Override
    protected Object doInBackground(Object[] objects) {//task主程序

        if (onExecute != null){
            onExecute.main();
        }

        return true;
    }

    @Override
    protected void onPostExecute(Object obj) {//task结束后

        if (time < 100){
            final Timer timer2 = new Timer();
            //final Object fo = o;
            timer2.scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    time++;

                    if (time >= 100){
                        timer2.cancel();
                        ((Activity)context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                taskfinish();
                            }
                        });


                    }

                }
            }, 0, pause);
        }
        else {
            taskfinish();
        }

        //super.onPostExecute(obj);
    }

    private void taskfinish(){
        dialog.dismiss();

        if (onExecute != null){
            onExecute.after();
        }

    }

    public interface OnExecute{
        void before();
        void main();
        void after();
    }


    public void setOnExecute(OnExecute onExecute) {
        this.onExecute = onExecute;
    }

}